﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Threading;
using Telerik.Windows.Controls;
using System.IO;
using InfoPick.UI.Comm;
using InfoPick.Lib.Log;

namespace InfoPick.UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            StyleManager.ApplicationTheme = new Windows7Theme();

            AppGlobal.InitXmlData();
            
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
        }


        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    Exception ex = e.ExceptionObject as Exception;
                    if (ex != null)
                    {
                        Tools.ShowMessage(false, "发生致命错误，请重试！");
                        string message = string.Format("{0} : message:{1}\r\n{2}", DateTime.Now, ex.Message, ex.StackTrace);
                        Log.WriteLog(message);
                    }
                    else
                    {
                        Tools.ShowMessage(false, "发生异常，请联系管理员！");
                    }
                }), null);
                Environment.Exit(-1);
            }
        }


        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                e.Handled = true;
                if (e.Exception != null)
                {
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        Tools.ShowMessage(false, "发生错误！" + e.Exception.Message);
                        string message = string.Format("{0} : message:{1}\r\n{2}", DateTime.Now, e.Exception.Message, e.Exception.StackTrace);
                        Log.WriteLog(message);
                    }), null);
                }
            }
        }


    }
}
